<style lang="less">
  .card_style {
    height: 100%;
    width: 100%;
    overflow: hidden;
    .ivu-card-body {
      padding: 0px;
    }
  }
  .page_style {
    margin-top: 10px;
    text-align: right;
  }
  .search-info-style {
    margin: 10px;
  }
  .new-btn-sty {
    margin-right: 5px;
    color: #fff;
    background-color: #235CA7;
    border-color: #235CA7;
    font-weight: 500;
  }
  .modal-form-input {
    width: 80%;
    margin-left: 50px;
  }
  .ivu-upload {
    width: 100%;
    .ivu-upload-select {
      padding: 0px;
    }
  }
</style>
<template>
  <Card class="card_style" :bordered="false" :dis-hover="true">
    <Row class="search-info-style">
      <Col span="6">
        <span style="text-al">姓名：</span>
        <Input style="width: 70%;" v-model="searchInfo.name" />
      </Col>
      <Col span="6">
        <span>身份证号：</span>
        <Input style="width: 70%;" v-model="searchInfo.cardno" />
      </Col>
      <Button class="new-btn-sty" @click="changePageNo(1)">
        <Icon type="ios-search" /> 搜索
      </Button>
      <Button class="new-btn-sty" @click="addPerson">
        <Icon type="md-add" /> 添加人员
      </Button>
      <Button class="new-btn-sty" @click="importModal.show=true">导入人员</Button>
    </Row>
    <Table border :columns="columns1" :data="datalist" >
      <template slot-scope="{ row, index }" slot="table-btns">
        <span style="margin-right: 5px">
          <Button type="info" size="small" @click="editInfo(row)">编辑</Button>
        </span>
        <span>
          <Button type="error" size="small" @click="deletePerson(row)">删除</Button>
        </span>
      </template>
    </Table>
    <Row v-if="loadData">
      <Col class="demo-spin-col" span="8" offset="8">
        <Spin fix>
          <Icon type="ios-loading" size=18 class="demo-spin-icon-load"></Icon>
          <div>数据正在加载</div>
        </Spin>
      </Col>
    </Row>
    <Page class="page_style" :total="searchInfo.totalnum" :current="searchInfo.currentPageNo"
          :page-size="searchInfo.currentPageSize" @on-change="changePageNo" show-total
          show-sizer @on-page-size-change="changePageSize"/>

    <Modal v-model="modalData.show" title="人员信息" width="800">
      <Form label-position="right" :label-width="120" ref="personInfo" :model="modalData.data"
            :rules="ruleInline" inline>
        <FormItem label="姓名：" prop="name" style="margin-left: 50px; width: 40%">
          <Input type="text" v-model="modalData.data.name"></Input>
        </FormItem>
        <FormItem label="性别：" style="width: 40%">
          <RadioGroup v-model="modalData.data.sex">
            <Radio label="男">男</Radio>
            <Radio label="女">女</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="生日：" style="margin-left: 50px; width: 40%">
          <Input type="text" v-model="modalData.data.birthday" placeholder="由身份证号计算得出" disabled></Input>
        </FormItem>
        <FormItem label="民族：" style="width: 38%">
          <Input type="text" v-model="modalData.data.folk" placeholder="例：汉族"></Input>
        </FormItem>
        <FormItem label="身份证号：" prop="cardno" class="modal-form-input">
          <Input type="text" v-model="modalData.data.cardno" :disabled="modalData.edit"></Input>
        </FormItem>
        <FormItem label="联系方式：" prop="mobile" class="modal-form-input">
          <Input type="text" v-model="modalData.data.mobile"></Input>
        </FormItem>
        <FormItem label="地址：" prop="address" class="modal-form-input">
          <Input type="text" v-model="modalData.data.address"></Input>
        </FormItem>
        <FormItem label="户籍地址：" class="modal-form-input">
          <Input type="text" v-model="modalData.data.domicile_address"></Input>
        </FormItem>
        <FormItem label="文化程度：" class="modal-form-input">
          <Input type="text" v-model="modalData.data.education"></Input>
        </FormItem>
        <FormItem label="婚姻状况：" class="modal-form-input">
          <Select v-model="modalData.data.marriage">
            <Option value="未婚">未婚</Option>
            <Option value="已婚">已婚</Option>
            <Option value="丧偶">丧偶</Option>
            <Option value="离婚">离异</Option>
            <Option value="未说明">未说明</Option>
          </Select>
        </FormItem>
        <FormItem label="政治面貌：" class="modal-form-input">
          <Select v-model="modalData.data.political_outlook">
            <Option value="群众">群众</Option>
            <Option value="中国共产党员">中国共产党员</Option>
            <Option value="中国共产党预备党员">中国共产党预备党员</Option>
            <Option value="中国共产主义青年团团员">中国共产主义青年团团员</Option>
            <Option value="中国国民党革命委员会会员">中国国民党革命委员会会员</Option>
            <Option value="中国民主同盟盟员">中国民主同盟盟员</Option>
            <Option value="中国民主建国会会员">中国民主建国会会员</Option>
            <Option value="中国民主促进会会员">中国民主促进会会员</Option>
            <Option value="中国农工民主党党员">中国农工民主党党员</Option>
            <Option value="中国致公党党员">中国致公党党员</Option>
            <Option value="九三学社社员">九三学社社员</Option>
            <Option value="台湾民主自治同盟盟员">台湾民主自治同盟盟员</Option>
            <Option value="无党派民主人士">无党派民主人士</Option>
          </Select>
        </FormItem>
        <FormItem label="职业：" class="modal-form-input">
          <Input type="text" v-model="modalData.data.occupation"></Input>
        </FormItem>
        <FormItem label="工作单位：" class="modal-form-input">
          <Input type="text" v-model="modalData.data.work_unit"></Input>
        </FormItem>
        <FormItem label="备注：" class="modal-form-input">
          <Input type="textarea" v-model="modalData.data.remarks"></Input>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="success" @click="savePerson">确认</Button>
        <Button type="error" @click="modalData.show=false">关闭</Button>
      </div>
    </Modal>

    <Modal v-model="importModal.show" width="1000" title="人员信息导入">
      <Row :gutter="16">
        <Col span="4">
          <Upload
            :loading="importModal.uploadLoading"
            :before-upload="handleBeforeUpload"
            action=""
            accept=".xls, .xlsx">
            <Button long icon="ios-cloud-upload-outline">选择文件</Button>
          </Upload>
        </Col>
        <Col span="4">
          <Button type="primary" @click="exportDataTmp" long>下载模板</Button>
        </Col>
        <Col span="4">
          <Button type="primary" @click="importData" long>开始导入</Button>
        </Col>
        <Col span="8" style="line-height: 32px;">
          共计：{{importModal.data.length}} 条 | 成功：{{importModal.successNum}} 条 | 失败：{{importModal.failNum}} 条
        </Col>
      </Row>
      <div>
      </div>
      <!-- <template>
        <Progress :percent="schedule" :stroke-width="5">
          <Icon type="checkmark-circled"></Icon>
          <span v-if="schedule === 0">未开始</span>
          <span v-if="schedule >0 && schedule <100">{{schedule}}%</span>
          <span v-if="schedule === 100">成功</span>
        </Progress>
      </template> -->
      <div style="height: auto; max-height: 400px; overflow: auto;">
        <Table border :columns="columnsImport" :data="importModal.data" :loading="importModal.tableLoading">
          <template slot-scope="{ row, index }" slot="import-result">
            {{row.import_type}}
          </template>
        </Table>
      </div>
      <div slot="footer">
        <Button type="error" @click="importModal.show=false">关闭</Button>
      </div>
    </Modal>

  </Card>
</template>
<script>
import { findUserList, getUserInfo, saveUserInfo, deleteUser } from '@/api/capital'
import excel from '@/libs/excel'
export default {
  components: {},
  data () {
    const validateCardno = (rule, value, callback) => {
      let format = /^(([1][1-5])|([2][1-3])|([3][1-7])|([4][1-6])|([5][0-4])|([6][1-5])|([7][1])|([8][1-2]))\d{4}(([1][9]\d{2})|([2]\d{3}))(([0][1-9])|([1][0-2]))(([0][1-9])|([1-2][0-9])|([3][0-1]))\d{3}[0-9xX]$/
      if (!format.test(value)) {
        callback(new Error('身份证号格式不正确'))
      } else {
        callback()
      }
    }
    return {
      loadData: true,
      searchInfo: {
        name: '',
        cardno: '',
        currentPageNo: 1,
        currentPageSize: 10
      },
      columns1: [
        { title: '序号', type: 'index', width: 80, align: 'center' },
        { title: '姓名', key: 'name', width: 100 },
        { title: '性别', key: 'sex', width: 90, align: 'center' },
        { title: '年龄', key: 'age', width: 90, align: 'center' },
        { title: '身份证号', key: 'cardno_en', width: 160 },
        { title: '联系方式', key: 'mobile', width: 140, align: 'center' },
        { title: '地址', key: 'address', minWidth: 120 },
        { title: '操作', align: 'center', slot: 'table-btns', width: 150 }
      ],
      columnsImport: [
        { title: '序号', type: 'index', width: 70, align: 'center' },
        { title: '姓名', key: 'name', width: 90 },
        { title: '性别', key: 'sex', width: 80, align: 'center' },
        { title: '民族', key: 'folk', width: 90, align: 'center' },
        { title: '身份证号', key: 'cardno', width: 160 },
        { title: '联系方式', key: 'mobile', width: 120, align: 'center' },
        { title: '地址', key: 'address', minWidth: 120 },
        { title: '结果', align: 'center', slot: 'import-result', width: 120 }
      ],
      datalist: [],
      ruleInline: {
        name: [
          { required: true, message: '请填写姓名', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请填写联系方式', trigger: 'blur' }
        ],
        cardno: [
          { required: true, message: '请填写身份证号', trigger: 'blur' },
          { validator: validateCardno, trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请填写地址', trigger: 'blur' }
        ]
      },
      modalData: { show: false, edit: true, data: {} },
      importModal: {
        show: false,
        uploadLoading: false,
        tableLoading: false,
        schedule: 0,
        data: [],
        successNum: 0,
        failNum: 0
      }
    }
  },
  computed: {
    companyCode () {
      return this.$store.state.user.severUserInfo.company_code
    }
  },
  methods: {
    exportDataTmp () {
      window.open('http://imgdl.tripln.top/webhdfs/v1/示例模板/示例.xlsx?op=OPEN&namenoderpcaddress=hadoop01:9000&offset=0')
    },
    importData () {
      if (!this.importModal.data || this.importModal.data.length === 0) {
        this.$Notice.warning({ title: '导入失败', desc: '无数据' })
        return
      }
      let that = this
      this.importModal.data.forEach(function (item, index) {
        saveUserInfo(item).then(res => {
          if (res.data.data) {
            item.import_type = '导入成功'
            that.importModal.successNum++
          } else {
            item.import_type = '导入失败：' + res.data.errmsg
            that.importModal.failNum++
          }
          that.$forceUpdate()
        })
      })
    },
    // 查询订单列表接口
    init (param) {
      param.pageNo = this.searchInfo.currentPageNo
      param.pageSize = this.searchInfo.currentPageSize
      findUserList(param).then(res => {
        if (res.data.data) {
          this.datalist = res.data.data.results
          this.searchInfo.totalnum = res.data.data.totalRecord
          let now_year = new Date().getFullYear()
          this.datalist.forEach(function (item, index) {
            if (item.cardno.length === 18) {
              item.cardno_en = item.cardno.substring(0, 6) + '********' + item.cardno.substring(14)
            } else if (item.cardno.length === 15) {
              item.cardno_en = item.cardno.substring(0, 6) + '******' + item.cardno.substring(12)
            } else {
              item.cardno_en = item.cardno
            }
            let year = parseInt(item.birthday.substring(0, 4))
            item.age = now_year - year
          })
          this.loadData = false
        } else {
          this.loadData = true
          this.$Notice.error({ title: '获取人员列表失败', desc: res.data.errmsg })
        }
      })
    },
    changePageSize (pageSize) {
      this.searchInfo.currentPageSize = pageSize
      let params = {
        name: this.searchInfo.name,
        cardno: this.searchInfo.cardno
      }
      this.init(params)
    },
    // 搜索按钮 || 切换页码
    changePageNo (pageNo) {
      this.searchInfo.currentPageNo = pageNo
      let params = {
        name: this.searchInfo.name,
        cardno: this.searchInfo.cardno
      }
      this.init(params)
    },
    addPerson () {
      this.modalData.data = { sex: '男' }
      this.modalData.edit = false
      this.modalData.show = true
    },
    editInfo (obj) {
      getUserInfo({ cardno: obj.cardno }).then(res => {
        if (res.data.data) {
          this.modalData.data = res.data.data
          this.modalData.show = true
          this.modalData.edit = true
        } else {
          this.$Notice.error({ title: '查询失败', desc: res.data.errmsg })
        }
      })
    },
    savePerson () {
      this.$refs.personInfo.validate((valid) => {
        if (valid) {
          saveUserInfo(this.modalData.data).then(res => {
            if (res.data.data) {
              this.$Notice.success({ title: '成功', desc: '' })
              this.modalData.show = false
              this.changePageNo(1)
            } else {
              this.$Notice.error({ title: '失败', desc: res.data.errmsg })
            }
          })
        } else {
          this.$Notice.error({ title: '信息错误', desc: '请填写正确的人员信息' })
        }
      })
    },
    deletePerson (obj) {
      this.$Modal.confirm({
        title: '删除后信息将无法找回，确认删除吗？',
        onOk: () => {
          deleteUser(obj).then(res => {
            if (res.data.data) {
              this.$Notice.success({ title: '成功', desc: '' })
              this.changePageNo(1)
            } else {
              this.$Notice.error({ title: '失败', desc: res.data.errmsg })
            }
          })
        }
      })
    },
    // 上传 excel
    handleBeforeUpload (file) {
      const fileExt = file.name.split('.').pop().toLocaleLowerCase()
      if (fileExt === 'xlsx' || fileExt === 'xls') {
        this.readFile(file)
        // this.file = file
      } else {
        this.$Notice.warning({
          title: '文件类型错误',
          desc: '文件：' + file.name + '不是EXCEL文件，请选择后缀为.xlsx或者.xls的EXCEL文件。'
        })
      }
      return false
    },
    // 处理解析上传数据
    readFile (file) {
      const reader = new FileReader()
      reader.readAsArrayBuffer(file)
      reader.onloadstart = e => {
        this.importModal.uploadLoading = true
        this.importModal.tableLoading = true
      }
      reader.onerror = e => {
        this.$Message.error('文件读取出错')
      }
      reader.onload = e => {
        this.$Message.info('文件读取成功')
        this.importModal.data = []
        this.importModal.successNum = 0
        this.importModal.failNum = 0
        const data = e.target.result
        const { header, results } = excel.read(data, 'array')
        console.log(header, 'header')
        let that = this
        results.forEach(function (item, index) {
          let tmpData = {
            name: item['姓名'],
            sex: item['性别'],
            folk: item['民族'],
            cardno: item['身份证号'],
            mobile: item['联系方式'],
            address: item['地址'],
            domicile_address: item['户籍地址'],
            education: item['文化程度'],
            marriage: item['婚姻状况'],
            political_outlook: item['政治面貌'],
            occupation: item['职业'],
            work_unit: item['工作单位'],
            remarks: item['备注'],
            import_type: '未导入'
          }
          that.importModal.data.push(tmpData)
        })
        this.importModal.uploadLoading = false
        this.importModal.tableLoading = false
      }
    }
  },
  watch: {
    'modalData.show' (newValue, oldValue) {
      // 每次关闭人员信息框时重置表单校验
      if (!newValue) {
        this.$refs.personInfo.resetFields()
      }
    }
  },
  mounted () {
    this.init({})
  }
}
</script>
